/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { Asset, AssetManager, __private } from 'cc';
import { reference, asset } from '../core';

const TAG = 'lcc/pack/pack-loader.ts';

/**
 * @zh
 * 包加载器基类
 */
export class PackLoaderBase {
    /**
     * @zh
     * 包的名称
     */
    private _name: string = null!;

    /**
     * @zh
     * 获得包名称
     */
    get name() {
        return this._name;
    }

    /**
     * @zh
     * 资源包对象
     */
    private _bundle: AssetManager.Bundle = null!;

    /**
     * @zh
     * 获得包资源
     */
    get bundle() {
        return this._bundle;
    }

    /**
     * @zh
     * 构造包加载器
     *
     * @param name - 包的名称
     * @param bundle - 资源包对象
     */
    constructor(name: string, bundle: AssetManager.Bundle) {
        this._name = name;
        this._bundle = bundle;
    }

    /**
     * @zh
     * 加载操作
     */
    onLoad() {}

    /**
     * @zh
     * 加载包内资源
     *
     * @param path - 资源路径
     * @param type - 资源类型
     */
    loadAsset<T extends Asset>(path: string, type: __private._cocos_core_asset_manager_shared__AssetType<T>) {
        return asset.loadAsset<T>(path, type, this._bundle);
    }

    /**
     * @zh
     * 释放未使用的资源
     */
    releaseUnusedAssets() {
        this._bundle.releaseUnusedAssets();
    }
}

/**
 * @zh
 * 获得指定包引用的KEY
 *
 * @param pack 包名
 * @param path 引用路径
 * @returns KEY值
 */
export function GetPackRefKey(pack: string, path: string) {
    return `${pack}://${path}`;
}

/**
 * @zh
 * 装饰器 - 包加载器
 *
 * @param pack 包名
 */
export function packloader(pack: string) {
    return function (target: Function) {
        reference.set(GetPackRefKey(pack, 'PackLoader'), target);
    };
}
